package com.ruoyi.web.controller.admin;


import com.ruoyi.admin.service.IDifyDataSourceService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/dify")
@Slf4j
@RequiredArgsConstructor
public class DifyDataSourceController {


    private final IDifyDataSourceService difyDataSourceService;

    /**
     * 获取所有信息
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> allMessage = difyDataSourceService.getAllMessage(9999, 1, 1, "", "", "");

        Workbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet();

        for (int i = 0; i < allMessage.size(); i++) {
            Row row = sheet.createRow(i);
            Map<String, Object> map = allMessage.get(i);
            row.createCell(0).setCellValue(String.valueOf(map.get("id")));
            row.createCell(1).setCellValue(String.valueOf(map.get("app_id")));
            row.createCell(2).setCellValue(String.valueOf(map.get("name")));
            row.createCell(3).setCellValue(String.valueOf(map.get("query")));
            row.createCell(4).setCellValue(String.valueOf(map.get("answer")));
            row.createCell(5).setCellValue(String.valueOf(map.get("conversation_id")));
            row.createCell(6).setCellValue(String.valueOf(map.get("created_at")));
            row.createCell(7).setCellValue(String.valueOf(map.get("updated_at")));
            row.createCell(8).setCellValue(String.valueOf(map.get("session_id")));
        }
        response.setContentType("application/x-msdownload");
        String encode = URLEncoder.encode("数据.xlsx", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename=" + encode);
        workbook.write(response.getOutputStream());
        workbook.close();
    }


    /**
     * 获取所有信息
     */
    @GetMapping("/getAllMessage")
    public TableDataInfo getAllMessage(@RequestParam(defaultValue = "20") int pageSize,
                                       @RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "1") int userId,
                                       @RequestParam(defaultValue = "") String message,
                                       @RequestParam(defaultValue = "") String startTime,
                                       @RequestParam(defaultValue = "") String endTime) {

        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows(difyDataSourceService.getAllMessage(pageSize, pageNum, userId, message, startTime, endTime));
        dataInfo.setTotal(difyDataSourceService.getCount(message, startTime, endTime));
        return dataInfo;
    }


    /**
     * 获取所有信息
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse httpServletRequest,
                            @RequestParam(defaultValue = "") String message,
                            @RequestParam(defaultValue = "") String startTime,
                            @RequestParam(defaultValue = "") String endTime) throws IOException {

        List<Map<String, Object>> allMessage = difyDataSourceService.getAllMessage(9999999, 1, 1, message, startTime, endTime);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("用户或账号");
        Cell cell1 = row.createCell(1);
        cell1.setCellValue("标题");
        Cell cell2 = row.createCell(2);
        cell2.setCellValue("回答");
        Cell cell3 = row.createCell(3);
        cell3.setCellValue("创建时间");
        int startRow = 1;
        for (Map<String, Object> stringObjectMap : allMessage) {
            row = sheet.createRow(startRow);
            row.createCell(0).setCellValue((String) stringObjectMap.get("session_id"));
            try {
                row.createCell(1).setCellValue((String) stringObjectMap.get("query"));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            row.createCell(2).setCellValue((String) stringObjectMap.get("answer"));
            row.createCell(3).setCellValue(((Timestamp) stringObjectMap.get("created_at")).toString());
            startRow++;
        }
        httpServletRequest.setContentType("application/x-msdownload");
        String encode = URLEncoder.encode("历史问答记录.xlsx", StandardCharsets.UTF_8);
        httpServletRequest.setHeader("Content-Disposition", "attachment; filename=" + encode);
        workbook.write(httpServletRequest.getOutputStream());
        workbook.close();
    }

    @GetMapping("/getMessage")
    public List<Map<String, Object>> getAllMessage(@RequestParam(defaultValue = "") String conversation_id
    ) {
        return difyDataSourceService.getMessage(conversation_id);
    }

    @GetMapping("/getMessageNode")
    public List<Map<String, Object>> getMessageNode(@RequestParam(name = "messageId", defaultValue = "") String messageId) {
        return difyDataSourceService.getMessageNode(messageId);
    }

    @GetMapping("/getContent")
    public List<Map<String, Object>> getContent(@RequestParam(defaultValue = "") String knowledgeIds) {
        return difyDataSourceService.getContent(knowledgeIds);
    }


    /**
     * 获取所有的用户会话记录
     */
    @PostMapping("/getAllUserMessageContent")
    public AjaxResult getAllUserMessageContent(@RequestParam(name = "token", defaultValue = "") String token,
                                               @RequestParam(name = "keywords", defaultValue = "") String keywords) {
        return AjaxResult.success("查询成功", difyDataSourceService.getAllUserMessageContent(token, keywords));
    }


    /**
     * 获取当前会话的记录
     */
    @PostMapping("/getDifyConversationMessage")
    public AjaxResult getDifyConversationMessage(@RequestParam(name = "token", defaultValue = "") String token,
                                                 @RequestParam(name = "conversationId", defaultValue = "") String conversationId) {
        return AjaxResult.success("查询成功", difyDataSourceService.getDifyConversationMessage(token, conversationId));
    }
}
